package com.ruoyi.develop.goodsSalebuyall.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.service.IGoodsOrderInService;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.develop.goodsSalebuy.domain.GoodsSalebuy;
import com.ruoyi.develop.goodsSalebuy.mapper.GoodsSalebuyMapper;
import com.ruoyi.develop.goodsSalebuy.service.IGoodsSalebuyService;
import com.ruoyi.develop.goodsSaledo.domain.GoodsSaledo;
import com.ruoyi.develop.goodsSaledo.mapper.GoodsSaledoMapper;
import com.ruoyi.develop.lvBuy.domain.LvBuy;
import com.ruoyi.develop.lvBuy.service.ILvBuyService;
import com.ruoyi.develop.lvDaohuoDetail.domain.LvDaohuoDetail;
import com.ruoyi.develop.lvDaohuoDetail.service.ILvDaohuoDetailService;
import com.ruoyi.develop.lvRuku.domain.LvRuku;
import com.ruoyi.develop.lvRuku.mapper.LvRukuMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.goodsSalebuyall.domain.GoodsSalebuyall;
import com.ruoyi.develop.goodsSalebuyall.service.IGoodsSalebuyallService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购单合计Controller
 * @author qh
 * @date 2024-08-09
 */
@RestController
@RequestMapping("/goodsSalebuyall/goodsSalebuyall")
public class GoodsSalebuyallController extends BaseController {
    @Autowired
    private IGoodsSalebuyallService goodsSalebuyallService;
    @Resource
    private GoodsSalebuyMapper goodsSalebuyMapper;
    @Resource
    private LvRukuMapper lvRukuMapper;
    @Resource
    private GoodsSaledoMapper goodsSaledoMapper;
    @Resource
    private IGoodsOrderInService goodsOrderInService;

    @Resource
    private ILvBuyService lvBuyService;
    @Autowired
    private IGoodsSalebuyService goodsSalebuyService;

    @Autowired
    private ILvDaohuoDetailService iLvDaohuoDetailService;

    @Autowired
    private IGoodsSaleService iGoodsSaleService;
    /**
     * 查询采购单合计列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSalebuyall:query')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsSalebuyall entity) {
        startPage();
        List<GoodsSalebuyall> list = goodsSalebuyallService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 导出采购单合计列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSalebuyall:export')")
    @Log(title = "采购单合计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodsSalebuyall entity) {
        List<GoodsSalebuyall> list = goodsSalebuyallService.selectList(entity);
        ExcelUtil<GoodsSalebuyall> util = new ExcelUtil<GoodsSalebuyall>(GoodsSalebuyall. class);
        util.exportExcel(response, list, "采购单合计数据");
    }

    /**
     * 获取采购单合计详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSalebuyall:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(goodsSalebuyallService.selectById(id));
    }

    /**
     * 新增采购单合计
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSalebuyall:add')")
    @Log(title = "采购单合计", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody GoodsSalebuyall entity) {
        return toAjax(goodsSalebuyallService.insert(entity));
    }

    /**
     * 修改采购单合计
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSalebuyall:edit')")
    @Log(title = "采购单合计", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody GoodsSalebuyall entity) {
        return toAjax(goodsSalebuyallService.update(entity));
    }

    @PutMapping("/editZj")
    public AjaxResult editZj(@RequestBody GoodsSalebuyall entity) {
        return toAjax(goodsSalebuyallService.editZj(entity));
    }
    /**
     * 删除采购单合计
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSalebuyall:remove')")
    @Log(title = "采购单合计", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(goodsSalebuyallService.deleteByIds(ids));
    }


    @Log(title = "删除采购产品", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteCg/{ids}")
    public AjaxResult deleteProject(@PathVariable String[] ids) {
        return toAjax(goodsSalebuyallService.deleteCg(ids[0]));
    }

    @Log(title = "删除采购退货产品", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteBuyAllReturn/{ids}")
    public AjaxResult deleteBuyAllReturn(@PathVariable String[] ids) {
        return toAjax(goodsSalebuyallService.deleteBuyAllReturn(ids[0]));
    }


    //提交采购订单
    @PostMapping("/submitCgd")
    public AjaxResult submitCgd(@Validated @RequestBody GoodsSalebuyall entity) {
        goodsSalebuyallService.submitCgd(entity);
        return AjaxResult.success("选择完成！");
    }

    @PostMapping("/submitBuyReturn")
    public AjaxResult submitBuyReturn(@Validated @RequestBody LvBuy entity) {
        goodsSalebuyallService.addBuyReturn(entity);
        return AjaxResult.success("选择完成！");
    }

    //更新采购订单
    @PostMapping("/updateCgd")
    public AjaxResult updateCgd(@Validated @RequestBody GoodsSalebuyall entity) {
        goodsSalebuyallService.updateCgd(entity);
        return AjaxResult.success("选择完成！");
    }


    //提交采购订单
    @PostMapping("/submitBuySelf")
    public AjaxResult submitBuySelf(@Validated @RequestBody LvBuy lvBuy) {
        goodsSalebuyallService.submitBuySelf(lvBuy);
        return AjaxResult.success("新增完成！");
    }


    //更新自采采购订单
    @PutMapping("/updateBuySelf")
    public AjaxResult updateBuySelf(@Validated @RequestBody LvBuy entity) {
        goodsSalebuyallService.updateBuySelf(entity);
        return AjaxResult.success("修改完成！");
    }




    @DeleteMapping(value = "/zhijianwancheng/{ids}")
    public AjaxResult zhijianwancheng(@PathVariable("ids") String[] ids) {
        for(String id :ids){
            GoodsSalebuyall goodsSalebuyall=goodsSalebuyallService.selectById(id);
            goodsSalebuyall.setStatus(BusinessConstants.SALE_TYPE_8);
            goodsSalebuyall.setZhijianDate(new Date());
            goodsSalebuyall.setIsZhijian(BusinessConstants.STATUS_YES);
            goodsSalebuyall.setZhijianName(getLoginUser().getUsername());
            goodsSalebuyallService.update(goodsSalebuyall);
        }
        return AjaxResult.success("质检完成！");
    }

    @DeleteMapping(value = "/updateRuku/{ids}")
    public AjaxResult updateRuku(@PathVariable("ids") String[] ids) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvRukuMapper.selectMaxCode(today);
        if(StringUtils.isNotBlank(codeMaxString)){
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString)+1+"";
        }else{
            codeMaxString = today+"0001";
        }
        LvRuku lvruku=new LvRuku();
        lvruku.setId(IdUtils.fastSimpleUUID());
        lvruku.setNos(codeMaxString);
        lvruku.setState(BusinessConstants.SALE_TYPE_9);
        lvruku.setCreateBy(SecurityUtils.getUsername());
        lvruku.setCreateTime(DateUtils.getNowDate());
        lvruku.setRukuDate(new Date());
        lvruku.setRukuid(getLoginUser().getUserId());
        lvruku.setRukupeople(getLoginUser().getUsername());
        lvRukuMapper.insert(lvruku);

        for(String id :ids){
            GoodsSalebuyall goodsSalebuyall=goodsSalebuyallService.selectById(id);
            goodsSalebuyall.setStatus(BusinessConstants.SALE_TYPE_9);
            goodsSalebuyall.setRukuno(lvruku.getNos());
            goodsSalebuyall.setRukudate(lvruku.getRukuDate());
            goodsSalebuyall.setRukuren(lvruku.getRukupeople());
            goodsSalebuyallService.update(goodsSalebuyall);

            GoodsOrderIn goodsOrderIn=goodsOrderInService.selectById(goodsSalebuyall.getGoodsId());
            goodsOrderIn.setId(null);
            goodsOrderIn.setRukudate(lvruku.getRukuDate());
            goodsOrderIn.setRukuno(lvruku.getNos());
            goodsOrderIn.setRukuren(lvruku.getRukupeople());
            goodsOrderIn.setName(goodsSalebuyall.getGoodsName());
            goodsOrderIn.setBrand(goodsSalebuyall.getGoodsBrand());//明细
            goodsOrderIn.setModel(goodsSalebuyall.getGoodModel());//型号
            goodsOrderIn.setUnit(goodsSalebuyall.getUnit());
            goodsOrderIn.setRemark(goodsSalebuyall.getRemark());
            goodsOrderIn.setCostPriceTax(goodsSalebuyall.getGoodsBuyPrice());
            goodsOrderIn.setCount(goodsSalebuyall.getShengyu());
            goodsOrderIn.setDun(goodsSalebuyall.getDun());
            goodsOrderIn.setCostTax(goodsSalebuyall.getGoodsBuyTotal());
            goodsOrderIn.setZhijiandan(goodsSalebuyall.getZhijiandan());
            goodsOrderInService.insertOrderUpdateArea(goodsOrderIn);

            List<GoodsSalebuy> goodsSalebuyList=goodsSalebuyMapper.selectByCgallId(id);
            for(GoodsSalebuy goodsSalebuy : goodsSalebuyList){
                goodsSalebuy.setRukuno(lvruku.getNos());
                goodsSalebuy.setRukudate(lvruku.getRukuDate());
                goodsSalebuy.setRukuren(lvruku.getRukupeople());
                goodsSalebuy.setRukuId(lvruku.getId());
                goodsSalebuy.setStatus(BusinessConstants.SALE_TYPE_9);
                goodsSalebuyMapper.update(goodsSalebuy);
                GoodsSaledo goodsSaledo=goodsSaledoMapper.selectById(goodsSalebuy.getQinggouId());
                goodsSaledo.setStatus(BusinessConstants.SALE_TYPE_9);
                goodsSaledo.setRukuno(lvruku.getNos());
                goodsSaledo.setRukuId(lvruku.getId());
                goodsSaledo.setRukudate(lvruku.getRukuDate());
                goodsSaledoMapper.update(goodsSaledo);
            }
        }
        return AjaxResult.success("入库完成！");
    }



    /**
     * 采购单下的产品是否全部到货
     */
    @GetMapping("/checkGoodsAllArrived")
    public AjaxResult checkGoodsAllArrived(GoodsSalebuyall entity) {
        int  unArrivedCount = goodsSalebuyallService.getUnarrivedGoodsCount(entity);
        return AjaxResult.success(unArrivedCount);
    }


    /**
     * 采购单 全部到货 （并且更新订单的产品状态）
     */
    @GetMapping("/goodsAllArrived")
    public AjaxResult goodsAllArrived(GoodsSalebuyall entity) {
        entity = goodsSalebuyallService.selectById(entity.getId());
        entity.setDaohuoStatus(BusinessConstants.GOODS_ARRIVAL_STATUS_ALL);
        int  i = goodsSalebuyallService.update(entity);
        goodsSalebuyService.updateGoodsSalebuyBuruku(entity.getId(),BusinessConstants.GOODS_ARRIVAL_STATUS_BURUKU);
        String buyId = entity.getMainId();
        LvBuy lvBuy = lvBuyService.selectById(buyId);
        // 如果订单下产品都到货了 更新 采购单状态
        /*GoodsSalebuyall goodsSalebuyall = new GoodsSalebuyall();
        goodsSalebuyall.setMainId(entity.getMainId());*/
        List<GoodsSalebuyall> goodsSalebuyalls =  goodsSalebuyallService.selectMainId(buyId);
        String buyArrivalStatus = "";
        // 订单下的所有产品 都到货 更新订单为到货；部分到货 更新订单为部分到货；都未到货 更新为 未到货；
        int arrivalAllCount = 0;
        int partArrivalCount = 0;
        int notArrivalCount = 0;
        for (GoodsSalebuyall buy:goodsSalebuyalls) {
            if(BusinessConstants.GOODS_ARRIVAL_STATUS_PART.equals(buy.getDaohuoStatus())){
                partArrivalCount++;
            }
            if(BusinessConstants.GOODS_ARRIVAL_STATUS_NOT.equals(buy.getDaohuoStatus())){
                notArrivalCount++;
            }
            if(BusinessConstants.GOODS_ARRIVAL_STATUS_ALL.equals(buy.getDaohuoStatus())){
                arrivalAllCount++;
            }
        }
        if(arrivalAllCount == goodsSalebuyalls.size()){ // 全部到货
            buyArrivalStatus = BusinessConstants.GOODS_ARRIVAL_STATUS_ALL;
        }else if(notArrivalCount == goodsSalebuyalls.size()) { // 全部未到货
            buyArrivalStatus = BusinessConstants.GOODS_ARRIVAL_STATUS_NOT;
        }else{
            buyArrivalStatus = BusinessConstants.GOODS_ARRIVAL_STATUS_PART; // 部分到货
        }
        lvBuy.setArrivalStatus(buyArrivalStatus);
        lvBuyService.update(lvBuy);
        List<GoodsSalebuy> goodsSalebuyList=goodsSalebuyService.selectByCgallId(entity.getId());
        for(GoodsSalebuy goodsSalebuy:goodsSalebuyList){
            GoodsSale goodsSale=iGoodsSaleService.selectById(goodsSalebuy.getGoodsSaleId());
            if(goodsSale!=null){
                goodsSale.setStatus(BusinessConstants.SALE_TYPE_10);
                iGoodsSaleService.update(goodsSale);
            }
        }
        return AjaxResult.success(i);
    }

    /**
     * 采购产品退货不入库（需要退回款项？？？？？）
     */
    @GetMapping("/tuihuoBuruku")
    public AjaxResult tuihuoBuruku(GoodsSalebuyall entity) {
        BigDecimal unitPrice=entity.getGoodsBuyPrice();
        entity = goodsSalebuyallService.selectById(entity.getBuyAllId());
        entity.setTuihuoType(BusinessConstants.GOODS_ARRIVAL_STATUS_BURUKU);//退货不入库
        entity.setDaohuoStatus(BusinessConstants.GOODS_ARRIVAL_STATUS_ALL);//全部到货
        int  i = goodsSalebuyallService.update(entity);
        goodsSalebuyService.updateGoodsSalebuyBuruku(entity.getId(),BusinessConstants.GOODS_ARRIVAL_STATUS_BURUKU);

        //退货不入库（更新到货明细表）
        LvDaohuoDetail lvDaohuoDetail=new LvDaohuoDetail();
        lvDaohuoDetail.setInspectState(BusinessConstants.INSPECT_STATE_YES);//已质检
        lvDaohuoDetail.setStorageState(BusinessConstants.STORAGE_STATE_UN);//未入库
        lvDaohuoDetail.setStorageDate(new Date());
        lvDaohuoDetail.setTuihuoType(BusinessConstants.GOODS_ARRIVAL_STATUS_BURUKU);//退货不入库
        lvDaohuoDetail.setSaleId(entity.getId());//采购合计id
        lvDaohuoDetail.setGoodId(entity.getGoodsId());
        lvDaohuoDetail.setDaohuoCount(entity.getShengyuDaohuoCount());
        lvDaohuoDetail.setUnitPrice(unitPrice);
        lvDaohuoDetail.setTotalPrice(unitPrice.multiply(entity.getShengyuDaohuoCount()));
        lvDaohuoDetail.setGoodsSaleId(entity.getGoodsSaleId());//订单产品id
        lvDaohuoDetail.setProjectId(entity.getProjectId());
        lvDaohuoDetail.setProjectNo(entity.getProjectNo());
        iLvDaohuoDetailService.insert(lvDaohuoDetail);
        GoodsSale goodsSale=iGoodsSaleService.selectById(entity.getGoodsSaleId());
        if(goodsSale!=null){
            goodsSale.setStatus(BusinessConstants.SALE_TYPE_88);
            iGoodsSaleService.update(goodsSale);
        }
        return AjaxResult.success(i);
    }
    /**
     * 采购产品退货待入库（进入待入库）
     */
    @GetMapping("/tuihuoRuku")
    public AjaxResult tuihuoRuku(GoodsSalebuyall entity) {
        BigDecimal unitPrice=entity.getGoodsBuyPrice();
        entity = goodsSalebuyallService.selectById(entity.getBuyAllId());
        entity.setTuihuoType(BusinessConstants.GOODS_ARRIVAL_STATUS_RUKU);//退货不入库
        entity.setDaohuoStatus(BusinessConstants.GOODS_ARRIVAL_STATUS_ALL);//全部到货（？？？？？？？？？）
        int  i = goodsSalebuyallService.update(entity);
        goodsSalebuyService.updateGoodsSalebuyBuruku(entity.getId(),BusinessConstants.GOODS_ARRIVAL_STATUS_RUKU);

        //退货入库（更新到货明细表）
        LvDaohuoDetail lvDaohuoDetail=new LvDaohuoDetail();
        lvDaohuoDetail.setInspectState(BusinessConstants.INSPECT_STATE_YES);//已质检
        lvDaohuoDetail.setStorageState(BusinessConstants.STORAGE_STATE_UN);//未入库
        lvDaohuoDetail.setStorageDate(new Date());
        lvDaohuoDetail.setTuihuoType(BusinessConstants.GOODS_ARRIVAL_STATUS_RUKU);//退货不入库
        lvDaohuoDetail.setSaleId(entity.getId());//采购合计id
        lvDaohuoDetail.setGoodId(entity.getGoodsId());
        lvDaohuoDetail.setDaohuoCount(entity.getShengyuDaohuoCount());
        lvDaohuoDetail.setUnitPrice(unitPrice);
        lvDaohuoDetail.setTotalPrice(unitPrice.multiply(entity.getShengyuDaohuoCount()));
        lvDaohuoDetail.setGoodsSaleId(entity.getGoodsSaleId());//订单产品id
        lvDaohuoDetail.setProjectId(entity.getProjectId());
        lvDaohuoDetail.setProjectNo(entity.getProjectNo());
        iLvDaohuoDetailService.insert(lvDaohuoDetail);
        GoodsSale goodsSale=iGoodsSaleService.selectById(entity.getGoodsSaleId());
        if(goodsSale!=null){
            goodsSale.setStatus(BusinessConstants.SALE_TYPE_99);
            iGoodsSaleService.update(goodsSale);
        }
        return AjaxResult.success(i);
    }
}
